package com.example.websocketrabbitmq.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Controller
public class MessageController {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    private int count = 0;

    // 处理广播消息
    @MessageMapping("/broadcast")
    @SendTo("/topic/public")
    public String handleBroadcast(String message) {
        return "[广播] " + message;
    }

    // 处理点对点消息
    @MessageMapping("/private")
    public void handlePrivate(@Payload String message, SimpMessageHeaderAccessor headerAccessor) {
        String user = null;
        if (headerAccessor.getUser() != null) {
            user = headerAccessor.getUser().getName();
        }
        if (user != null) {
            simpMessagingTemplate.convertAndSendToUser(
                    user,
                    "/queue/private",
                    "[私信] " + message
            );
        }
    }

    // 接收客户端发送的消息
    @MessageMapping("/send")
    public void handleMessage(String message) {
        // 处理消息后广播到订阅地址
        messagingTemplate.convertAndSend("/topic/messages", "服务端回复：" + message);
    }

    // 定时推送示例（需主类加@EnableScheduling）
    @Scheduled(fixedRate = 5000)
    public void sendPeriodicMessage() {
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
        count++;
        messagingTemplate.convertAndSend("/topic/notifications", "定时消息" + formattedDateTime + ":" + count);
    }

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
}
